package controllers

import (
	"github.com/astaxie/beego"
	"../utils"
	"github.com/globalsign/mgo/bson"
	"encoding/json"
	"fmt"
)

type LoggerController struct {
	beego.Controller
}

type person struct {
	Name string `json:"name"`
	Age int		`json:"age"`
}

type JsonResponse struct {
	Data []person `json:"data"`
}

func (c *LoggerController) Get() {
	dbs := [...]string{"logger", "just a test"}
	jsonDbs, _ := json.Marshal(dbs)
	c.Data["dbs"] = string(jsonDbs)

	db := c.Ctx.Input.Param(":db")
	c.Data["db"] = db
	c.TplName = "logger.html"
	fmt.Println(db)

	keyword := c.GetString("keyword")
	c.Data["keyword"] = keyword

	pageSize := 10
	page, _ := c.GetInt("page")
	if page == 0 {
		page = 1
	}
	c.Data["page"] = page

	var result []interface{}
	collection := utils.GetCollection(db)
	var count = 0

	fields := bson.M{
		"id": 1,
		"pathinfo": 1,
		"method": 1,
		"full_url": 1,
		"doc_url": 1,
		"tag": 1,
		"summary": 1,
		"created_at": 1,

		"accumulated_duration_str": 1,
		"queries_count": 1,
	}
	if keyword != "" {
		or := []bson.M{
			{"pathinfo": bson.RegEx{keyword, "i"}},
			{"tag": bson.RegEx{keyword, "i"}},
			{"summary": bson.RegEx{keyword, "i"}},
		}

		_ = collection.Find(bson.M{"$or": or}).Select(fields).
			Skip((page - 1) * pageSize).Limit(pageSize).Sort("-created_at").All(&result)

		count, _ = collection.Find(bson.M{"$or": or}).Count()
	} else {
		_ = collection.Find(nil).Select(fields).
			Skip((page - 1) * pageSize).Limit(pageSize).Sort("-created_at").All(&result)
		count, _ = collection.Count()
	}

	encoded, _ := json.Marshal(result)
	c.Data["list"] = string(encoded)

	c.Data["Page"] = utils.PageUtil(count, page, pageSize)

	c.TplName = "logger.html"
}

func (c *LoggerController) LoggerDetail() {
	db := c.Ctx.Input.Param(":db")

	id := c.GetString("id")
	var result interface{}
	collection := utils.GetCollection(db)
	_ = collection.FindId(bson.ObjectIdHex(id)).One(&result)

	c.Data["json"] = &result

	c.ServeJSON()
}